package com.feimt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feimt.dto.SetmealDto;
import com.feimt.exce.CustomException;
import com.feimt.mapper.SetmealMapper;
import com.feimt.pojo.Setmeal;
import com.feimt.pojo.SetmealDish;
import com.feimt.service.SetmealDishService;
import com.feimt.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Transactional
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    @Override
    public void saveSetmealAndDish(SetmealDto setmealDto) {
        //1. 保存菜品基本信息 - setmealId
        this.save(setmealDto);
        //2. setmealId Setmealdish
        //2.1 setmealDto 获取所有的菜
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map(item ->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        //3. Setmealdish 批量新增
        setmealDishService.saveBatch(setmealDishes);
    }

    @Override
    public void deleteByIdsAndDishs(List<Long> ids) {
        //1.这些套餐是否正在售卖
//        select count(*) form setmeal where id in (idsxxx) and status = 1
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.in(Setmeal::getId,ids);
        qw.eq(Setmeal::getStatus,1);
        int count = this.count(qw);
        if(count > 0 ){
            System.out.println("不能删，正在售卖");
            throw new CustomException("不能删，正在售卖");
        }

        //2.删除套餐
        this.removeByIds(ids);

        //3.删除关联菜品setealDish   setmealId id (idsxxx)
        LambdaQueryWrapper<SetmealDish> qw2 = new LambdaQueryWrapper<>();
        qw2.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(qw2);

    }
}
